/**
 * 
 */
package org.xelnaga.defiler.web.controller.contentlet;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xelnaga.defiler.domain.CategoryModel;
import org.xelnaga.defiler.domain.ContentletModel;
import org.xelnaga.defiler.domain.FieldModel;
import org.xelnaga.defiler.domain.FieldModel.FieldTypeEnum;
import org.xelnaga.defiler.domain.FieldWrapper;
import org.xelnaga.defiler.domain.StructureModel;
import org.xelnaga.defiler.service.CategoryService;
import org.xelnaga.defiler.service.FieldService;
import org.xelnaga.defiler.web.util.SimpleKeyValueBean;

/**
 * @author qijb
 *
 */
@Component
public class ContentletWebSupport {
    @Autowired
    private FieldService fieldService;
    @Autowired
    private CategoryService categoryService;
	/**
	 * 
	 */
	public ContentletWebSupport() {
		// TODO Auto-generated constructor stub
	}

	public Map<String, List<SimpleKeyValueBean>> getStructureFieldCategories(List<FieldModel> fields){
        //Search field category list.
        Map<String, List<SimpleKeyValueBean>> map = new HashMap<String, List<SimpleKeyValueBean>>();
        for(FieldModel field : fields) {
        	FieldTypeEnum typeEnum = FieldTypeEnum.getInstance(field.getFieldType());
        	if(null != typeEnum) {
        		
        		switch(typeEnum) {
        		case CATEGORY :
        		case MULTICATEGORY:
        			List<SimpleKeyValueBean> list = new ArrayList<SimpleKeyValueBean>();
        			if(StringUtils.isNotBlank(field.getFieldValues())) {
        				List<CategoryModel> catList = categoryService.getListByParentInode(Long.valueOf(field.getFieldValues()), false);
        				for(CategoryModel cat : catList) {
        					list.add(new SimpleKeyValueBean(cat.getInode(), cat.getTitle()));
        				}
        			}
        			map.put(field.getVelocityVarName(), list);
        			break;      			
        		case CHECKBOX: 
        			if(StringUtils.isNotBlank(field.getFieldValues())) {
        				String value = StringUtils.replace(field.getFieldValues(), "[(\\r\\n)\\n\\s]", "");
    					if(StringUtils.isNotBlank(value)) {
    						String[] kv = StringUtils.split(value, '|');
    						field.setFieldValues(kv[1]);
    					}
        			}
    				break;
        		case SELECT:
        			if(StringUtils.isNotBlank(field.getFieldValues())) {
        				List<SimpleKeyValueBean> selectList = new ArrayList<SimpleKeyValueBean>();
        				String[] values = StringUtils.split(field.getFieldValues(), "[(\\r\\n)\\n\\s]");
        				for(String value : values) {
        					if(StringUtils.isNotBlank(value)) {
        						String[] kv = StringUtils.split(value, '|');
        						selectList.add(new SimpleKeyValueBean(kv[0], kv[1]));
        					}
        				}
        				map.put(field.getVelocityVarName(), selectList);
        			}
        			break;
        		}
        	}
        }
		return map;
	}

	/**
	 * Get the structure defined value in contentlet.
	 * @param contentlet
	 * @return
	 */
	public List<FieldWrapper> getContentletFieldValues(ContentletModel contentlet) {
		StructureModel structure = contentlet.getStructure();
		List<FieldWrapper> result = new ArrayList<FieldWrapper>();
		List<FieldModel> fields = fieldService.getByStructureInode(structure.getInode());
		for(FieldModel field : fields) {
			if(StringUtils.isNotBlank(field.getFieldContentlet())) {
				try {
					FieldTypeEnum typeEnum = FieldTypeEnum.getInstance(field.getFieldType());
					//Process category and multi category field.
	    			if(null != typeEnum && 
	    					(typeEnum == FieldTypeEnum.CATEGORY || typeEnum == FieldTypeEnum.MULTICATEGORY)) {
	    				String[] arrays = field.getFieldContentlet().split("_");
	    				String value = BeanUtils.getProperty(contentlet, arrays[0] + StringUtils.capitalize(arrays[1]));
	    				if(StringUtils.isNotBlank(value)) {
	    					arrays = value.split(",");
	    					Long[] ids = new Long[arrays.length];
	    					for(int i=0;i<arrays.length;i++) {
	    						ids[i] = Long.valueOf(arrays[i]);
	    					}
	    					List<CategoryModel> categories = categoryService.getListByIds(ids);
	    					result.add(new FieldWrapper(field, categories));
	    				}
	    			} else {
						String value = null;
						String[] arrays = field.getFieldContentlet().split("_");
						if(null != arrays && arrays.length == 2) {
							value = BeanUtils.getProperty(contentlet, arrays[0] + StringUtils.capitalize(arrays[1]));
						} else {
							value = BeanUtils.getProperty(contentlet, field.getFieldContentlet());
						}
	    				result.add(new FieldWrapper(field, value));
	    			}
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}
}
